package com.company.aicrawlers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.Product;
import com.company.aicrawlers.entity.ProductCompetitor;
import com.company.aicrawlers.mapper.ProductCompetitorMapper;
import com.company.aicrawlers.mapper.ProductMapper;
import com.company.aicrawlers.service.ProductCompetitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 产品-竞品关联服务实现类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@Service
public class ProductCompetitorServiceImpl implements ProductCompetitorService {
    
    @Autowired
    private ProductCompetitorMapper productCompetitorMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public List<Product> getCompetitors(Long ourProductId, String competitorType, String strength) {
        // 检查产品是否存在且为我方产品
        Product ourProduct = productMapper.selectById(ourProductId);
        if (ourProduct == null) {
            throw new BusinessException("产品不存在");
        }
        if (ourProduct.getIsOurProduct() != 1) {
            throw new BusinessException("该产品不是我方产品，无法查询竞品");
        }
        
        // 查询竞品列表
        List<Product> competitors = productCompetitorMapper.selectCompetitorsByOurProductId(
                ourProductId, competitorType, strength);
        
        log.info("查询产品竞品，产品ID: {}, 竞品数量: {}", ourProductId, competitors.size());
        return competitors;
    }
    
    @Override
    public List<Product> getOurProducts(Long competitorProductId) {
        // 检查产品是否存在且为竞品
        Product competitor = productMapper.selectById(competitorProductId);
        if (competitor == null) {
            throw new BusinessException("产品不存在");
        }
        if (competitor.getIsOurProduct() != 0) {
            throw new BusinessException("该产品不是竞品");
        }
        
        // 查询我方产品列表
        List<Product> ourProducts = productCompetitorMapper.selectOurProductsByCompetitorId(competitorProductId);
        
        log.info("反向查询我方产品，竞品ID: {}, 我方产品数量: {}", competitorProductId, ourProducts.size());
        return ourProducts;
    }
    
    @Override
    public List<Product> getOurProductsByCompetitor(Long competitorId) {
        // 与getOurProducts相同，但命名更清晰
        return getOurProducts(competitorId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addCompetitorRelation(Long ourProductId, Long competitorId, String competitorType,
                                      String strength, String dimension, Integer sortOrder, String remark) {
        // 参数校验
        if (ourProductId == null || competitorId == null) {
            throw new BusinessException("产品ID不能为空");
        }
        
        if (ourProductId.equals(competitorId)) {
            throw new BusinessException("不能将产品关联到自己");
        }
        
        // 检查我方产品
        Product ourProduct = productMapper.selectById(ourProductId);
        if (ourProduct == null) {
            throw new BusinessException("我方产品不存在");
        }
        if (ourProduct.getIsOurProduct() != 1) {
            throw new BusinessException("产品ID " + ourProductId + " 不是我方产品");
        }
        
        // 检查竞品
        Product competitor = productMapper.selectById(competitorId);
        if (competitor == null) {
            throw new BusinessException("竞品不存在");
        }
        if (competitor.getIsOurProduct() != 0) {
            throw new BusinessException("产品ID " + competitorId + " 不是竞品");
        }
        
        // 检查是否已存在关联
        LambdaQueryWrapper<ProductCompetitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCompetitor::getOurProductId, ourProductId)
               .eq(ProductCompetitor::getCompetitorProductId, competitorId);
        ProductCompetitor exist = productCompetitorMapper.selectOne(wrapper);
        
        if (exist != null) {
            throw new BusinessException("该竞品关联已存在");
        }
        
        // 创建关联
        ProductCompetitor relation = new ProductCompetitor();
        relation.setOurProductId(ourProductId);
        relation.setCompetitorProductId(competitorId);
        relation.setCompetitorType(competitorType != null ? competitorType : "direct");
        relation.setStrength(strength != null ? strength : "medium");
        relation.setDimension(dimension);
        relation.setSortOrder(sortOrder != null ? sortOrder : 0);
        relation.setRemark(remark);
        relation.setCreateTime(LocalDateTime.now());
        relation.setUpdateTime(LocalDateTime.now());
        
        productCompetitorMapper.insert(relation);
        
        log.info("添加竞品关联成功，我方产品: {}, 竞品: {}, 类型: {}", 
                ourProduct.getProductName(), competitor.getProductName(), competitorType);
        
        return relation.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchConfigCompetitors(Long ourProductId, List<ProductCompetitor> competitors) {
        if (competitors == null || competitors.isEmpty()) {
            return;
        }
        
        // 先删除已有的竞品关联
        LambdaQueryWrapper<ProductCompetitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCompetitor::getOurProductId, ourProductId);
        productCompetitorMapper.delete(wrapper);
        
        // 批量插入新的关联
        for (ProductCompetitor competitor : competitors) {
            competitor.setOurProductId(ourProductId);
            addCompetitorRelation(
                    ourProductId,
                    competitor.getCompetitorProductId(),
                    competitor.getCompetitorType(),
                    competitor.getStrength(),
                    competitor.getDimension(),
                    competitor.getSortOrder(),
                    competitor.getRemark()
            );
        }
        
        log.info("批量配置竞品成功，我方产品ID: {}, 竞品数量: {}", ourProductId, competitors.size());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCompetitorRelation(Long ourProductId, Long competitorId) {
        LambdaQueryWrapper<ProductCompetitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCompetitor::getOurProductId, ourProductId)
               .eq(ProductCompetitor::getCompetitorProductId, competitorId);
        
        int count = productCompetitorMapper.delete(wrapper);
        
        if (count == 0) {
            throw new BusinessException("竞品关联不存在");
        }
        
        log.info("移除竞品关联成功，我方产品ID: {}, 竞品ID: {}", ourProductId, competitorId);
    }
    
    @Override
    public ProductCompetitor getRelation(Long ourProductId, Long competitorId) {
        LambdaQueryWrapper<ProductCompetitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCompetitor::getOurProductId, ourProductId)
               .eq(ProductCompetitor::getCompetitorProductId, competitorId);
        
        return productCompetitorMapper.selectOne(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRelation(ProductCompetitor relation) {
        if (relation.getId() == null) {
            throw new BusinessException("关联ID不能为空");
        }
        
        ProductCompetitor exist = productCompetitorMapper.selectById(relation.getId());
        if (exist == null) {
            throw new BusinessException("竞品关联不存在");
        }
        
        relation.setUpdateTime(LocalDateTime.now());
        productCompetitorMapper.updateById(relation);
        
        log.info("更新竞品关联成功，ID: {}", relation.getId());
    }
}

